package com.redis.util;

import cn.hutool.json.JSON;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;

/**
 * @Description
 * @Author lizhilong
 * @Date 2020/12/7 16:14
 */
@Component
@Slf4j
public class RedisUtil {

    @Resource
    private RedissonClient redissonClient;

    /**
     * 添加对象并设置过期时间
     */
    public <V> void addObject(String key, V v, Long timeOut, TimeUnit timeUnit) {
        RBucket<V> bucket = redissonClient.getBucket(key);
        bucket.set(v, timeOut, timeUnit);
    }

    /**
     * 获取对象
     */
    public <T> T getObject(String key, Class<T> clazz) {
        RBucket<T> bucket = redissonClient.getBucket(key);
        return bucket.get();
    }

    /**
     * 添加map
     */
    public <K, V> boolean addMap(String key, Map<K, V> valueMap, Long timeOut, TimeUnit timeUnit) {
        RLock fairLock = redissonClient.getFairLock("lock_" + key);
        try {
            while (fairLock.tryLock()) {
                RMap<K, V> map = redissonClient.getMap(key);
                valueMap.forEach(map::fastPut);
                map.expire(timeOut, timeUnit);
                return true;
            }
        } catch (Exception e) {
            log.info("获取锁信息异常");
            return false;
        } finally {
            fairLock.unlock();
        }
        return false;
    }

    /**
     * 获取整个map
     */
    public <K, V> Map<K, V> getMap(String key, Class<K> kClass, Class<V> vClass) {
        RMap<K, V> map = redissonClient.getMap(key);
        Map<K, V> kvMap = map.readAllMap();
        return kvMap;
    }

    /**
     * 获取map 某个key 的值
     */
    public <K, V> V getMapValue(String key, K k, Class<V> vClass) {
        RMap<K, V> map = redissonClient.getMap(key);
        V v = map.get(k);
        return v;
    }
}
